<template>
  <div class="blockchain-container">
    <!-- 最新区块信息（每分钟自动更新） -->
    <el-card class="card" shadow="hover">
      <div slot="header" class="card-header">
        <i class="el-icon-time" />
        <span>最新区块信息最新更新时间：{{ lastUpdateTime | formatDateTime }}</span>
      </div>
      <el-skeleton v-if="latestBlockInfo.loading" :rows="6" animated class="mt-20" />
      <el-descriptions v-if="latestBlockInfo.success" :column="2" border class="block-info">
        <el-descriptions-item label="区块高度"><el-tag type="info">#{{ latestBlockInfo.data.blockNumber.toLocaleString() }}</el-tag></el-descriptions-item>
        <el-descriptions-item label="区块哈希"><el-tooltip :content="latestBlockInfo.data.hash"><span class="hash">{{ latestBlockInfo.data.hash | truncateHash }}</span></el-tooltip></el-descriptions-item>
        <el-descriptions-item label="时间戳">{{ latestBlockInfo.data.timestamp | formatTimestamp }}</el-descriptions-item>
        <el-descriptions-item label="交易数量"><el-badge :value="latestBlockInfo.data.transactionCount" :max="999" class="badge-item" /></el-descriptions-item>
        <el-descriptions-item label="矿工地址"><el-tooltip :content="latestBlockInfo.data.miner"><span class="hash">{{ latestBlockInfo.data.miner | truncateHash }}</span></el-tooltip></el-descriptions-item>
        <el-descriptions-item label="区块难度">{{ latestBlockInfo.data.difficulty | formatNumber }}</el-descriptions-item>
        <el-descriptions-item label="区块大小">{{ latestBlockInfo.data.size | formatSize }} 字节</el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 静态信息展示 -->
    <el-card class="card static-info" shadow="hover">
      <div slot="header" class="card-header">
        <i class="el-icon-info" />
        <span>区块链合约信息</span>
      </div>
      <el-descriptions :column="2" border>
        <el-descriptions-item label="合约地址">
          <el-tooltip :content="staticInfo.contractAddress" placement="top">
            <span class="hash">{{ staticInfo.contractAddress | truncateHash }}</span>
          </el-tooltip>
        </el-descriptions-item>
        <el-descriptions-item label="管理员账户">
          <el-tooltip :content="staticInfo.accountAddress" placement="top">
            <span class="hash">{{ staticInfo.accountAddress | truncateHash }}</span>
          </el-tooltip>
        </el-descriptions-item>
      </el-descriptions>
    </el-card>

    <!-- 包含查询任务记录和区块信息查询的行 -->
    <el-row :gutter="20" class="mt-20">
      <el-col :md="12">
        <!-- 优化后的查询任务记录 -->
        <el-card class="card task-search" shadow="hover">
          <div class="search-wrapper">
            <el-input 
              v-model="searchTaskId" 
              placeholder="请输入任务ID查询训练记录" 
              clearable 
              class="enhanced-search-input"
              @clear="handleClearSearch"
            >
              <el-button 
                slot="append" 
                type="primary" 
                icon="el-icon-search" 
                @click="handleSearchRecord"
              />
            </el-input>
          </div>
          <el-alert v-if="recordData.error" :title="`查询失败: ${recordData.error}`" type="error" show-icon class="mt-20" />
          <el-descriptions v-if="recordData.success" title="记录详情" :column="2" border class="mt-20">
            <el-descriptions-item label="数据集名称">{{ recordData.data.datasetName }}</el-descriptions-item>
            <el-descriptions-item label="任务ID">{{ recordData.data.taskId }}</el-descriptions-item>
            <el-descriptions-item label="批量大小">{{ recordData.data.batchSize }}</el-descriptions-item>
            <el-descriptions-item label="聚合次数">{{ recordData.data.aggregationCount }}</el-descriptions-item>
            <el-descriptions-item label="训练准确率"><el-tag type="success">{{ recordData.data.lastTrainAccuracy }}%</el-tag></el-descriptions-item>
            <el-descriptions-item label="测试准确率"><el-tag type="info">{{ recordData.data.lastTestAccuracy }}%</el-tag></el-descriptions-item>
            <el-descriptions-item label="区块哈希" :span="2">
              <el-tooltip :content="recordData.data.hash" placement="top">
                <span class="hash">{{ recordData.data.hash | truncateHash }}</span>
              </el-tooltip>
            </el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
      <el-col :md="12">
        <!-- 区块信息查询 -->
        <el-card shadow="hover">
          <div slot="header" class="card-header"><i class="el-icon-document" /><span>区块查询</span></div>
          <el-input v-model="blockNumber" placeholder="请输入区块高度" clearable @clear="handleClearBlockNumber">
            <el-button slot="append" icon="el-icon-search" type="primary" @click="handleGetBlockInfo" />
          </el-input>
          <el-skeleton v-if="blockInfo.loading" :rows="3" animated class="mt-20" />
          <el-descriptions v-if="blockInfo.success" :column="1" class="mt-20">
            <el-descriptions-item label="哈希">{{ blockInfo.block.hash | truncateHash }}</el-descriptions-item>
            <el-descriptions-item label="时间戳"><el-tag type="info">{{ blockInfo.block.timestamp | formatTimestamp }}</el-tag></el-descriptions-item>
            <el-descriptions-item label="交易数"><el-badge :value="blockInfo.block.transactionCount" class="badge-item" /></el-descriptions-item>
          </el-descriptions>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import {
  getRecord,
  getBlockAndContractInfo,
  getLatestBlockInfo,
} from "../../web3/fl";

export default {
  filters: {
    truncateHash: (v) => v,
    formatTimestamp(timestamp) {
      const date = new Date(timestamp * 1000);
      return `${date.toLocaleDateString()} ${date.toLocaleTimeString()}`;
    },
    formatDateTime(timestamp) {
      return new Date(timestamp).toLocaleTimeString();
    },
    formatSize: (v) => new Intl.NumberFormat().format(v),
    formatNumber: (v) => v.toLocaleString(),
  },
  data() {
    return {
      staticInfo: {
        contractAddress: "0x89205A3A3b2A69De6Dbf7f01ED13B2108B2c43e7",
        accountAddress: "0x358AA13c52544ECCEF6B0ADD0f801012ADAD5eE3"
      },
      searchTaskId: "",
      recordData: { success: false },
      blockNumber: "",
      blockInfo: { success: false, loading: false },
      latestBlockInfo: { success: false, loading: false },
      lastUpdateTime: null,
      refreshInterval: null
    };
  },
  mounted() {
    this.handleGetLatestBlockInfo();
    this.refreshInterval = setInterval(() => {
      this.handleGetLatestBlockInfo();
    }, 60000);
  },
  beforeDestroy() {
    clearInterval(this.refreshInterval);
  },
  methods: {
    async handleSearchRecord() {
      if (!this.searchTaskId) return this.$message.warning("请输入任务ID");
      try {
        this.recordData = await getRecord(this.searchTaskId);
      } catch (error) {
        this.$notify.error({
          title: "查询失败",
          message: error.message,
        });
      }
    },
    async handleGetBlockInfo() {
      if (!this.blockNumber) return this.$message.warning("请输入区块高度");
      try {
        this.blockInfo.loading = true;
        this.blockInfo = await getBlockAndContractInfo(parseInt(this.blockNumber));
      } catch (error) {
        this.$notify.error({
          title: "查询失败",
          message: error.message,
        });
      } finally {
        this.blockInfo.loading = false;
      }
    },
    async handleGetLatestBlockInfo() {
      try {
        this.latestBlockInfo.loading = true;
        const result = await getLatestBlockInfo();
        this.latestBlockInfo = result;
        this.lastUpdateTime = new Date();
      } catch (error) {
        console.error('获取区块信息失败:', error);
        this.$notify.error({
          title: "更新失败",
          message: "最新区块信息获取失败"
        });
      } finally {
        this.latestBlockInfo.loading = false;
      }
    },
    handleClearSearch() {
      this.recordData = { success: false };
    },
    handleClearBlockNumber() {
      this.blockInfo = { success: false };
    }
  }
};
</script>

<style lang="scss" scoped>
.blockchain-container {
  padding: 0px;
  background-color: #f5f7fa;
  min-height: 100vh;
  display: grid;
  grid-gap: 20px;
}

.card {
  margin-bottom: 0;

}

.task-search {
  ::v-deep .el-card__header {
    background: linear-gradient(45deg, #f0f7ff, #e6f3ff);
    border-bottom: 2px solid #409EFF;
  }

  .search-wrapper {
    max-width: 600px;
    margin: 0 auto;
    text-align: center;
  }

  .search-title {
    color: #606266;
    font-size: 16px;
    margin-bottom: 15px;
  }

  .enhanced-search-input {
    ::v-deep .el-input__inner {
      height: 48px;
      border-radius: 24px;
      padding: 0 25px;
      font-size: 16px;
      border-color: #409EFF;
    }

    ::v-deep .el-input-group__append {
      border-radius: 0 24px 24px 0;
      background: #409EFF;
      padding: 0 30px;
      border: none;
      
      .el-button {
        color: white;
        font-size: 20px;
        padding: 12px 20px;
      }
    }
  }

  .search-tip {
    color: #909399;
    font-size: 12px;
  }
}

.static-info {
  ::v-deep .el-card__header {
    background: linear-gradient(45deg, #f8f9fa, #e9ecef);
  }
  .hash {
    font-family: monospace;
    color: #606266;
    font-weight: 500;
    letter-spacing: 0.5px;
  }
}

.mt-20 {
  margin-top: 20px;
}

.hash {
  font-family: monospace;
  color: #409EFF;
  cursor: pointer;
  &:hover {
    text-decoration: underline;
  }
}

.badge-item ::v-deep .el-badge__content {
  font-size: 12px;
  height: 18px;
  line-height: 18px;
  padding: 0 6px;
  background-color: #67C23A;
}

.block-info {
  ::v-deep .el-descriptions-item__label {
    width: 120px;
    font-weight: 500;
    color: #606266;
  }
}

.update-time {
  font-size: 12px;
  color: #909399;
  text-align: right;
  padding: 0 10px;
}

@media (max-width: 768px) {
  .blockchain-container {
    grid-template-columns: 1fr;
  }
  
  .enhanced-search-input {
    ::v-deep .el-input__inner {
      font-size: 14px !important;
    }
  }
}
</style>